
package datastream.recordset
{
 	/**
	 * @auth Chunning
	 * @purpose for data storing
	 * @date 2009-2-4
	 * */	
	
	
	dynamic public class RecordSet
	{
		//START
		private var xmlData:XML;
		
		public var attributes:Object;
						
		//CONSTRUCTOR
		public function RecordSet(data:XML)
		{
			
			this.xmlData = data;
				
			this.save(data);
									
		}
			
		
		//save data
		public function save(data:XML):void
		{
									
			 this.getAttributes(data);
			 
			 if(data.hasComplexContent())
			 {
			 	
			 	this.saveNode(data.children(),this);
			
			 }
			 
			 
		}
		
		//save the attributes of xml
		private function getAttributes(data:XML):void
		{
			
			this.attributes = new Object;
						
						
			for(var i:int = 0;i < data.attributes().length();i++)
			{
				
				this.attributes[data.attributes()[i].localName()] = data.attributes()[i].toString();
								
			}
						
		}	
		
		
		//save xml node (recursion)
		private function saveNode(datalist:XMLList,target:RecordSet):void
		{
			
			var node:RecordSet;
									
			for(var i:int = 0;i < datalist.length();i++)
			{
				
				node = new RecordSet(datalist[i] as XML);
				
				if(!target.hasOwnProperty(datalist[i].name()))
				{

					target[datalist[i].name()] = [node];					
					
				}else{
						
					target[datalist[i].name()].push(node);
						
				}				
				
			}
			
		}
		
		//override toString function of Object
		public function toString():String
		{
						
			return this.xmlData.toString();			
			
		}
		
		public function toXMLString():String
		{
			
			return this.xmlData.toXMLString();
			
		}
		
		//optimize the structure...
		public function optimize(...special):void
		{
													
			for(var prop:String in this)
			{
									
				if(this[prop] is Array)
				{
				
					for(var i:int = 0;i < this[prop].length;i++)
					{
						
						if(this[prop][i] is RecordSet)
						{
							
							this[prop][i].optimize(special);
							
						}
						
					}
																			
					if(this[prop].length == 1 && (special.join(",") + ",").indexOf(prop.toString() + ",")== -1)
					{
											
						this[prop] = this[prop][0];
						
					}	
					
				}
				
				
			}
			
		}
		
		
		//END
	}
}